package com.star.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.star.system.entity.RoleMenu;
import com.star.system.mapper.RoleMenuMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.system.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色菜单 服务实现类
 *
 * @author yangzj
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBatch(Long roleId, List<Long> menuIds) {
        this.saveBatch(menuIds.stream().map(c -> new RoleMenu()
                .setRoleId(roleId)
                .setMenuId(c))
                .collect(Collectors.toList()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBatch(Long roleId, List<Long> menuIds) {
        // 先删 再新增
        this.deleteByRoleIds(Collections.singletonList(roleId));
        // 保存角色菜单
        if (CollUtil.isNotEmpty(menuIds)) {
            this.saveBatch(roleId, menuIds);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByRoleIds(List<Long> roleIds) {
        this.lambdaUpdate().in(RoleMenu::getRoleId, roleIds).remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByMenuIds(List<Long> menuIds) {
        this.lambdaUpdate().in(RoleMenu::getMenuId, menuIds).remove();
    }
}
